<template>
	<ln-modal width="780px" :title="title" :mask-closable="false" :on-after-enter="onModalShow">
		<n-form
			ref="formRef"
			:model="form"
			:rules="rules"
			:disabled="props.modalType === ModalTypeEnum.detail"
			label-placement="left"
			require-mark-placement="right-hanging"
			label-width="100px"
		>
			<n-form-item :label="$t('common.roleName')" path="name">
				<n-input v-model:value="form.name" style="width: 190px" :placeholder="$t('msg.input')" />
			</n-form-item>
			<n-form-item :label="$t('common.roleState')" path="status">
				<n-switch v-model:value="form.status" :checked-value="0" :unchecked-value="1" />
			</n-form-item>
			<n-form-item :label="$t('common.describe')" path="description">
				<n-input
					v-model:value="form.description"
					type="textarea"
					style="width: 590px"
					:placeholder="$t('msg.select')"
				/>
			</n-form-item>
			<n-form-item :label="$t('common.rolePower')" path="authIds">
				<n-checkbox-group v-model:value="form.authIds">
					<n-space item-style="display: flex;">
						<n-checkbox
							v-for="item in allMenuRoles"
							:key="item.authName"
							class="check-item"
							:value="item.id"
							:label="$t(`menu.${item.authName}`)"
						/>
					</n-space>
				</n-checkbox-group>
			</n-form-item>
		</n-form>
		<template #footer>
			<div style="margin-top: 20px">
				<n-button
					v-if="props.modalType === ModalTypeEnum.detail"
					type="primary"
					@click="handleUpdateClick"
					>{{ $t('btn.update') }}</n-button
				>
				<n-button v-else type="primary" @click="handleSaveClick">{{ $t('btn.save') }}</n-button>
				<n-button @click="handleCloseClick(false)">{{ $t('btn.cancel') }}</n-button>
			</div>
		</template>
	</ln-modal>
</template>

<script lang="ts" setup>
import { useI18n } from 'vue-i18n';
import type { PropType } from 'vue';
import { useUserStore } from '@/store/modules/user';
import { addRole, updateRole } from '@/api/system/role';
import type { RoleListRow } from '@/api/system/role';
import { useMessage } from 'naive-ui';
import type { FormInst, FormRules } from 'naive-ui';
import { ModalTypeEnum, type ModalTypeParam } from '@/utils/enum';
import { titleFormatter } from '@/utils/formatter';

const { t } = useI18n();
const props = defineProps({
	modalData: {
		type: Object,
		default: () => {},
	},
	modalType: {
		type: [String, Number] as PropType<ModalTypeParam>,
		default: ModalTypeEnum.add,
	},
});
const emit = defineEmits(['close', 'update']);
const title = computed(() => titleFormatter(props.modalType));
// form
const formRef = ref<FormInst | null>();
const rules: FormRules = {
	name: { required: true, trigger: ['blur'], message: t('msg.input') },
	authIds: {
		required: true,
		trigger: ['blur'],
		message: t('msg.rolePower'),
		validator: (rule, value) => value.length > 0,
	},
};
const baseForm: RoleListRow = {
	name: '',
	status: 0,
	authIds: [],
	description: '',
	roleType: 'normal',
};
const form = ref<RoleListRow>({ ...baseForm });
const { allMenuRoles } = useUserStore();
const message = useMessage();

// 初始化
function onModalShow() {
	if (props.modalType === ModalTypeEnum.add) {
		form.value = { ...baseForm };
	} else {
		form.value = JSON.parse(JSON.stringify(props.modalData));
	}
}

// 保存
function handleSaveClick() {
	formRef.value?.validate(async errors => {
		if (!errors) {
			const params = { ...unref(form) };
			if (props.modalType === ModalTypeEnum.add) {
				await addRole(params);
			} else {
				await updateRole(params as RoleListRow);
			}
			message.success(t('msg.operationCompleted'));
			handleCloseClick(true);
		}
	});
}
// 关闭
function handleCloseClick(data?: boolean) {
	emit('close', data);
}
// 编辑
function handleUpdateClick() {
	emit('update');
}
</script>

<style lang="scss" scoped>
.check-item {
	width: 150px;
}
</style>
